<template>
  <div
    class="switch-main thumb"
    @click="changeStatus"
    :style="{
      background: color,
      width: `${width}${unit}`,
      height: `${height}${unit}`,
      'border-radius': `${height / 2}${unit}`,
    }"
  >
    <div
      :class="['switch-button']"
      :style="{
        width: `${buttonWidth}${unit}`,
        transform: `translate( ${
          is_act ? 'calc(' + width + unit + ' - 100%)' : '0px'
        }`,
      }"
    >
      <div class="switch-frame" :style="{ border: `1px solid ${color}` }"></div>
      <div class="circle" :style="{ background: color }"></div>
    </div>
  </div>
</template>
<script setup lang="ts" name="">
import { ref, computed, watch } from "vue";

interface Props {
  value?: boolean; //双向绑定的值
  width?: number; //switch宽度
  height?: number; //switch高度
  actColor?: string; //为true时的颜色
  tirColor?: string; //非true时的颜色
  buttonWidth?: number; //按钮宽度
  unit?: "px" | "rem" | "em"; //单位
}
const props = withDefaults(defineProps<Props>(), {
  value: true,
  width: 0.3073,
  height: 0.1302,
  actColor: `#18C240`,
  tirColor: `#8F8F8F`,
  buttonWidth: 0.1204,
  unit: "rem",
});

const emits = defineEmits<{
  (event: "update:value", value: boolean): void;
}>();

watch(
  () => props.value,
  (newValue) => {
    is_act.value = newValue;
  }
);

const color = computed((): string => {
  return is_act.value ? props.actColor : props.tirColor;
});

const is_act = ref<boolean>(props.value);

const changeStatus = () => {
  is_act.value = !is_act.value;
  emits("update:value", is_act.value);
};
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
